home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4351 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: hubcap.clemson.edu!hubcap!mjs
  2. From: mjs@hubcap.clemson.edu (M. J. Saltzman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: free space malloced to auto vars??
  5. Date: 3 Feb 96 21:26:43 GMT
  6. Organization: Clemson University
  7. Message-ID: <mjs.823382803@hubcap>
  8. References: <4eqf8m$smv@gsusgi1.gsu.edu> <9602032047.AA28443@dxmint.cern.ch>
  9. NNTP-Posting-Host: hubcap.clemson.edu
  10.  
  11. Dan Pop <danpop@mail.cern.ch> writes:
  12.  
  13. |matmrlx@gsusgi1.gsu.edu (Michael R. Lauer) writes:
  14. |>The general question is: if you malloc space for a pointer with automatic
  15. |>storage, should/must you free that space before leaving that scope?
  16.  
  17. |Yes.  However, I can't see any malloc call in your example.
  18. |>
  19. |>This seems obvious but it is giving me trouble. In this code:
  20. |>
  21. |>{
  22. |>    struct dirent *dp;
  23. |>    if ((dp = readdir() != NULL)
  24. |                  ^^^^^^^^^
  25. |This is a bad function call and it's likely to generate a segmentation
  26. |fault.
  27.  
  28. ObC:
  29. In addition, although it's hard to know for sure if this is a real
  30. problem (since the parentheses are unbalanced, so the fragment won't
  31. even compile), as it is written, this expression assigns dp the value
  32. 0 if readdir() returns NULL and 1 otherwise.  If readdir() returns a
  33. valid pointer, then when you go to free(dp), you will pass free() an
  34. invalid pointer.
  35.  
  36. |>    {
  37. |>    }
  38. |>    if (dp)            /* this seems to cause a segmentation fault */
  39. |>        free(dp);    /* when the enclosing function returns */
  40. |>}
  41.  
  42. I'll leave this excellent advice here:
  43.  
  44. |NEVER free a pointer initialized by a library function (with the possible
  45. |exception of the nonstandard strdup).
  46.  
  47. |Then call closedir() before returning from the function.  If the
  48. |documentation doesn't mention the need to call free(dp), then don't do it.
  49. |If you break the rules, you get what you deserve.
  50.  
  51. |BTW, readdir is not a standard C function, so the question should have been
  52. |posted to comp.unix.programmer.
  53. -- 
  54.         Matthew Saltzman
  55.         Clemson University Math Sciences
  56.         mjs@clemson.edu
  57.